#!/usr/bin/python

import time, sys

""" 

The nth term of the sequence of triangle numbers is given by, tn = 0.5 * n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
    
"""

def triangle(n):
    return int((n * (n + 1)) * 0.5)

def wordvalue(word):
    alphalut = dict(zip(['A', 'B', 'C', 'D', 'E', 'F','G','H','I','J','K',
        'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y', 'Z'], 
        [ num for num in range(1, 27) ] ))   
    wordvalue = sum([ alphalut[word[ind]] for ind in xrange(len(word)) ])
    
    return wordvalue

    
def main():
    start = time.time()
    
    wordfile = open('problem042_words.txt', 'rU')
    file = wordfile.read()
    wordfile.close()
    
    words = []
    for word in file.split(','):
        word = word.strip('"')
        words.append(word)
    
    trianglenums = [ triangle(n) for n in xrange(1, 100)]
    
    trianglewords = [ word for word in words if wordvalue(word) in trianglenums ]

    print len(trianglewords)
    
    print '{0:.2f} s'.format(time.time() - start)  

# solution: 162 in 0.03 s
    
    # testing code
    print
    print 'first 10 nums', trianglenums[:10]
    print wordvalue('S'), wordvalue('K'), wordvalue('Y')
    print trianglenums.index(wordvalue('SKY')) + 1
    
if __name__ == '__main__':
    main()

